package phasebook.impl;

import java.util.Calendar;
import java.util.Date;

import javax.ejb.Singleton;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import phasebook.client.PhasebookWSClientFactory;
import phasebook.client.RemotePhasebookService;
import phasebook.impl.entities.FinancialMovement;
import phasebook.impl.entities.User;

import lottery.LotteryGameWSClientFactory;
import lottery.RemoteLotteryGameService;
import lottery.msgs.LotteryResult;

@Singleton
public class PhasebookResultFetchingService {

	@PersistenceContext(unitName="phasebook")
	EntityManager em;
	
	RemoteLotteryGameService lotteryService = LotteryGameWSClientFactory.create("http://localhost:8080/phasebook_esb/http/Phasebook/WebWsEntry");

	RemotePhasebookService phasebookService = PhasebookWSClientFactory.create("http://localhost:8080/phasebook_esb/http/Phasebook/WebWsEntry");
	
	@EJB
	private MailSender mailSender;	
	
	private int previousMinute = 0;
	
	@Schedule(minute="*/3", hour="*", persistent=false)
	public void fetchResults() throws Exception {

		Calendar rightNow = Calendar.getInstance();
		int currentMinute = rightNow.get(Calendar.MINUTE);
				
		if(previousMinute > currentMinute || (previousMinute + 3) <= currentMinute){ // https://issues.jboss.org/browse/EJBTHREE-2229
			
			// Retrieve lottery results
			LotteryResult[] lotteryResults = lotteryService.retrieveResults(1); //PHASEBOOK SYSTEM ID = 1
			
			if(lotteryResults!=null){
				phasebookService.processResults(lotteryResults);
				phasebookService.notifyLotteryParticipants(lotteryResults);
			}
			
			previousMinute = currentMinute;
		}
	}

}
